import {AvatarDropdown, AvatarName, Footer} from '@/components';
import {LinkOutlined} from '@ant-design/icons';
import type {Settings as LayoutSettings} from '@ant-design/pro-components';
import {SettingDrawer} from '@ant-design/pro-components';
import {history, Link, RequestConfig, RunTimeLayoutConfig} from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import {errorConfig} from './requestErrorConfig';
import {getCurrentUserInfo} from "@/services/user/user";
import {MenuDataItem} from "@umijs/route-utils";
import sysmanage from '../public/icons/sysmanage.png'
import customerIcon from '../public/icons/customer.png'
import redpacketIcon from '../public/icons/redpacket.png'
import audioIcon from '../public/icons/audio.png'

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';

const SysManageIcon = () => {
  return <img src={sysmanage} alt="System Management" style={{width: '1em', height: '1em'}}/>;
};
const CustomerIcon = () => {
  return <img src={customerIcon} alt="Customer Management" style={{width: '1em', height: '1em'}}/>;
}
const RedPacketIcon = () => {
  return <img src={redpacketIcon} alt={'Red Packet'} style={{width: '1em', height: '1em'}}/>;
}
const AudioIcon = () => {
  return <img src={audioIcon} alt={'Red Packet'} style={{width: '1em', height: '1em'}}/>;
}

const menuMap = [
  {
    key: 'sysManage',
    name: '系统管理',
    path: '/sys',
    icon: <SysManageIcon/>,
  },
  {
    key: 'department',
    name: '门店管理',
    path: './department',
    component: './SysManage/Department',
  },
  {
    key: 'feekback',
    name: '意见反馈',
    path: './feedback',
    component: './Feedback',
  },
  {
    key: 'customerLevel',
    name: '顾客级别配置',
    path: './customer/level',
    component: './CustomerLevel',
  }, {
    key: 'wxGroupPower',
    name: '群管理',
    path: './group/list',
    component: './Group',
  }, {
    key: 'customerList',
    name: '顾客信息',
    path: '/customerInfo/customerList',
    component: './CustomerManage'
  },
  {
    key: 'rule',
    name: '邀请规则',
    path: '/customerInfo/rule',
    component: './CustomerManage/rule'
  },
  {
    key: 'inviterUpper',
    name: '邀请上限',
    path: '/customerInfo/inviterUpper',
    component: './CustomerManage/inviterUpper'
  },
  
  {
    key: 'customer',
    name: '顾客管理',
    path: '/customer',
    component: './customer',
    icon: <CustomerIcon/>,
  },  {
    key: 'audioList',
    name: '音频列表',
    path: '/aud/list',
    component: './Audio',
  }, {
    key: 'audioCategory',
    name: '音频类别',
    path: '/aud/category',
    component: './Audio/category',
  }, {
    key: 'redPacket',
    name: '红包报表',
    path: '/red',
    component: './RedPacket',
    icon: <RedPacketIcon/>,
  }, {
    key: 'redPacketReport',
    name: '红包统计',
    path: '/packet/statistics',
    component: './RedPacketStatistics',
    icon: <RedPacketIcon/>,
  }
]

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: USER.User;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
  menuData: MenuDataItem[];
}> {
  console.log('auth', sessionStorage.getItem('auth'))
  const buildMenuTree = async (menus) => {
    try {
      // 辅助函数，用于找到菜单项的子项
      const findChildren = (parent) => {
        return menus.filter(menu => menu.parentId === parent.id)
          .filter(menu => menuMap.filter(item => item.key === menu.name).length > 0)
          .map(menu => {
            const menuMapItems = menuMap.filter(item => item.key === menu.name);
            const menuItem: MenuDataItem = {
              path: menuMapItems[0].path,
              name: menu.title,
              icon: menuMapItems[0].icon,
              children: findChildren(menu)
            }
            menuItem.component = menuMapItems[0].component
            return menuItem;
          })
      };
      // const findChildren = (parent) => {
      //   return menus.filter(menu => menu.parentId === parent.id)
      //     .filter(menu => menuMap.filter(item => item.key === menu.name).length > 0)
      //     .map(menu => {
      //       const menuMapItems = menuMap.filter(item => item.key === menu.name);
      //       const menuItem: MenuDataItem = {
      //         path: menuMapItems[0].path,
      //         name: menu.title,
      //         icon: menuMapItems[0].icon,
      //         children: findChildren(menu)
      //       }
      //       menuItem.component = menuMapItems[0].component
      //       return menuItem;
      //     })
      // };

      // 过滤出顶层菜单项（假设顶层菜单的 parentId 为 0）
      const topMenus = menus.filter(menu => menu.parentId === 0)
        .filter(menu => menuMap.filter(item => item.key === menu.name).length > 0)
        .map(menu => {
          const menuMapItems = menuMap.filter(item => item.key === menu.name);
          const menuItem: MenuDataItem = {
            path: menuMapItems[0].path,
            name: menu.title,
            icon: menuMapItems[0].icon,
            children: findChildren(menu)
          }
          menuItem.component = menuMapItems[0].component
          return menuItem;
        });
      // topMenus.push({
      //   path: '/red/statistics',
      //   name: '红包统计',
      //   icon: <RedPacketIcon/>,
      //   component: './RedPacketStatistics',
      //   children: [],
      // })
      console.log(topMenus)
      return topMenus;
    } catch (error) {
      console.log(error)
      throw error
    }
  }
  const fetchUserInfo = async () => {
    try {
      const msg = await getCurrentUserInfo({
        skipErrorHandler: true,
      });
      console.log('current user', msg.data)
      return msg.data;
    } catch (error) {
      console.log(error)
      history.push(loginPath);
    }
    return undefined;
  };
  // 如果不是登录页面，执行
  const {location} = history;
  if (![loginPath, '/user/register', '/user/register-result'].includes(location.pathname)) {
    let currentUser = await fetchUserInfo();
    currentUser = {
      ...currentUser,
      name: currentUser.username,
      avatar: currentUser.icon,
    }
    const menuData = await buildMenuTree(currentUser.menus);
    console.log('menu data', menuData)
    console.log('current user', currentUser)
    // menuData.filter(item => item.name === '系统管理')[0].children.push({
    //   key: 'group',
    //   name: '群管理',
    //   path: './group/list',
    //   component: './Group',
    // })
    return {
      name: currentUser.username,
      avatar: currentUser.icon,
      fetchUserInfo,
      currentUser,
      settings: defaultSettings as Partial<LayoutSettings>,
      menuData: menuData,
    };
  }
  return {
    fetchUserInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({initialState, setInitialState}) => {
  return {
    menu: {
      locale: false,
      params: initialState,
      request: async () => {
        return initialState.menuData;
      },
    },
    actionsRender: () => [],//[<Question key="doc"/>, <SelectLang key="SelectLang"/>],
    avatarProps: {
      src: initialState?.currentUser?.avatar,
      title: <AvatarName/>,
      render: (_, avatarChildren) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    footerRender: () => <Footer/>,
    onPageChange: () => {
      const {location} = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    bgLayoutImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    links: isDev
      ? [
        <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
          <LinkOutlined/>
          <span>OpenAPI 文档</span>
        </Link>,
      ]
      : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          {isDev && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request: RequestConfig = {
  baseURL: API_URL,
  ...errorConfig,
  requestInterceptors: [
    (url, options) => {
      let headers = {
        ...options.headers,
      };

      const auth = sessionStorage.getItem('auth');
      if (auth) {
        //auth的结构是{token: 'xxx', tokenHead: 'xxx'}, 将请求的header中添加 'Authorization': tokenHead + ' ' + token
        const authInfo = JSON.parse(auth);
        headers = {
          ...headers,
          'Authorization': `${authInfo.tokenHead} ${authInfo.token}`,
        };
      }
      return {
        url,
        options: {...options, headers},
      };
    }
  ]
};


